package com.cmcc.linlaker.ui.mine;

import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.cmcc.linlaker.R;
import com.cmcc.linlaker.http.ApiDefine;
import com.cmcc.linlaker.ui.mine.adapter.RankingAdapter;
import com.cmcc.linlaker.ui.mine.bean.CheckCountBean;
import com.cmcc.linlaker.ui.mine.bean.CheckRankingBean;
import com.cmcc.linlaker.utils.BarUtils;
import com.cmcc.linlaker.utils.BasisTimesUtils;
import com.cmcc.linlaker.utils.IntentUtils;
import com.cmcc.linlaker.utils.SPHelper;
import com.cmcc.linlaker.utils.Tools;
import com.cmcc.linlaker.view.LineView;
import com.cmcc.linlaker.volley.GsonRequestHelper;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.view.LineChartView;

public class CheckInfoActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_info);

        BarUtils.initStatusBar(this);

        initView();
    }

    private TextView text_date;
    private LineChartView lineView;
    private Calendar calendar;

    private RecyclerView recycler_ranking;
    private RankingAdapter adapter;
    private List<CheckRankingBean.CheckRankingListBean> itemList = new ArrayList<>();

    private void initView() {
        calendar = Calendar.getInstance();
        text_date = findViewById(R.id.text_date);
        text_date.setText(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1));
        text_date.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        text_date.getPaint().setAntiAlias(true);//抗锯齿

        lineView = findViewById(R.id.chartView);

        recycler_ranking = findViewById(R.id.recycler_ranking);
        setRecyclerView(recycler_ranking, itemList);

        int year = calendar.get(Calendar.YEAR);
        String month = parseNumber(calendar.get(Calendar.MONTH) + 1);
        String date = year + "-" + month;
        getUserCount(date);
        getRanking(date);
    }

    private void setRecyclerView(final RecyclerView recycler_view, final List<CheckRankingBean.CheckRankingListBean> itemList) {
        recycler_view.setHasFixedSize(true);
        recycler_view.setLayoutManager(new LinearLayoutManager(this));

        recycler_view.setNestedScrollingEnabled(false);
        adapter = new RankingAdapter(this, itemList);
        recycler_view.setAdapter(adapter);
    }

    public void back(View view) {
        finish();
    }

    /**
     * 选择月份
     */
    public void selectMonth(View view) {
        showYearMonthPicker();
    }

    /**
     * 年月选择
     */
    private void showYearMonthPicker() {
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 2;
        BasisTimesUtils.showDatePickerDialog(this, true, "日期选择", year, month, 0,
                new BasisTimesUtils.OnDatePickerListener() {

                    @Override
                    public void onConfirm(int year, int month, int dayOfMonth) {
                        String dateStr = year + "-" + parseNumber(month);
                        text_date.setText(dateStr);

                        getUserCount(dateStr);
                        getRanking(dateStr);
                    }

                    @Override
                    public void onCancel() {
                    }
                }).setDayGone();
    }

    /**
     * 数字小于10 前面加0
     */
    private String parseNumber(int number) {
        if (number < 10) {
            return "0" + number;
        } else {
            return number + "";
        }
    }

    /**
     * 量化考核排行榜
     */
    private void getRanking(String date) {
        Log.e("date", date);

        GsonRequestHelper helper = new GsonRequestHelper(this);
        Map<String, String> params = new HashMap<>();
        params.put("createTime", date);

        helper.sendPOSTRequest(ApiDefine.PROBLEM_RANKING, CheckRankingBean.class, params, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    CheckRankingBean bean = (CheckRankingBean) data;

                    if (bean.code.equals("0")) {
                        itemList.clear();
                        itemList.addAll(bean.rows);
                        adapter.notifyDataSetChanged();
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(CheckInfoActivity.this);
                    }
                }
            }
        });
    }

    /**
     * 量化考核分布图
     */
    private void getUserCount(String date) {
        GsonRequestHelper helper = new GsonRequestHelper(this);
        Map<String, String> params = new HashMap<>();
        params.put("createTime", date);
        params.put("createBy", SPHelper.getUsername());

        helper.sendPOSTRequest(ApiDefine.PROBLEM_USER_COUNT, CheckCountBean.class, params, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    CheckCountBean bean = (CheckCountBean) data;

                    if (bean.code.equals("0")) {
                        if (bean.rows != null && bean.rows.size() > 0) {
                            Tools.setChartViewData(bean.rows, lineView);
                        }
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(CheckInfoActivity.this);
                    }
//                    setChartData(bean.rows);
                }
            }
        });
    }

    /**
     * 填充数据到line_chart
     */
    private void setChartData(List<CheckCountBean.CheckCountData> list) {
        List<PointValue> values = new ArrayList<>();
        //底部时间
        List<AxisValue> axisXBottomValues = new ArrayList<>();
        for (int i = 0; i < 31; i++) {
            axisXBottomValues.add(new AxisValue(i).setLabel(String.valueOf(i + 1)));
        }

        List<AxisValue> axisXLeftValues = new ArrayList<>();
        axisXLeftValues.add(new AxisValue(0).setLabel(String.valueOf(5)));
        axisXLeftValues.add(new AxisValue(1).setLabel(String.valueOf(10)));
        axisXLeftValues.add(new AxisValue(2).setLabel(String.valueOf(15)));

        for (int i = 0; i < list.size(); i++) {
            CheckCountBean.CheckCountData countData = list.get(i);
            int x = getDayInfo(countData.createTime);
            int y = Integer.parseInt(countData.count);
            values.add(new PointValue(x, y));
        }

        Line line = new Line(values);
        line.setColor(0xff3A9CE6);
        line.setHasLabels(false);//曲线的数据坐标是否加上备注
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状 这里是圆形 （
        //有三种 ：ValueShape.SQUARE(方形)  ValueShape.CIRCLE(圆形)  ValueShape.DIAMOND (菱形)）
        line.setPointRadius(3);//坐标点大小
        //line.setSquare(true);//是否以直角的形式显示线
        line.setCubic(true);//曲线是否平滑
        line.setFilled(false);//是否填充曲线的面积
        //line.setHasLabelsOnlyForSelected(false);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        line.setHasLines(true);//是否用直线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(true);//是否显示圆点 如果为false 则没有原点只有点显示
        line.setStrokeWidth(1);//设置线的宽度

        List<Line> lines = new ArrayList<>();
        lines.add(line);

        LineChartData data = new LineChartData();
        data.setBaseValue(Float.NEGATIVE_INFINITY);
        data.setLines(lines);

        //传入底部list数据
        Axis axisX = new Axis();
        //设置底部标题(自行选择) 只能设置在正中间
//        axisX.setName("日期");
        //底部标注是否斜着显示
        axisX.setHasTiltedLabels(false);
        //字体大小
        axisX.setTextSize(12);
        //字体颜色
        axisX.setTextColor(Color.parseColor("#666666"));
        //距离各标签之间的距离 (0-32之间)
        //axisX.setMaxLabelChars(4);
        //是否显示坐标线、如果为false 则没有曲线只有点显示
        axisX.setHasLines(false);
        axisX.setValues(axisXBottomValues);
        data.setAxisXBottom(axisX);

        //左边参数设置
        Axis axisY = new Axis();
        //axisY.setMaxLabelChars(6); //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数
        axisY.setTextSize(12);
        axisY.setTextColor(Color.parseColor("#666666"));
        axisY.setHasLines(false);
        axisY.setValues(axisXLeftValues);
        //设置坐标轴在左边
        data.setAxisYLeft(axisY);

        lineView.setLineChartData(data);
    }

    private int getDayInfo(String createTime) {
        String[] arr = createTime.split("-");
        String day = arr[2];
        return Integer.parseInt(day);
    }

    private List<AxisValue> getYList(List<CheckCountBean.CheckCountData> list) {
        List<AxisValue> axisXLeftValues = new ArrayList<>();
        List<Integer> axisXLeftIntValues = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            CheckCountBean.CheckCountData countData = list.get(i);
            if (!isHasSameData(axisXLeftIntValues, Integer.parseInt(countData.count))) {
                axisXLeftIntValues.add(Integer.parseInt(countData.count));
            }
        }

        Collections.sort(axisXLeftIntValues);

        for (int i = 0; i < axisXLeftIntValues.size(); i++) {
            axisXLeftValues.add(new AxisValue(i).setLabel(axisXLeftIntValues.get(i) + ""));
        }

        return axisXLeftValues;
    }

    private boolean isHasSameData(List<Integer> axisXLeftValues, int data) {
        boolean isHasSame = false;
        for (Integer value : axisXLeftValues) {
            if (value == data) {
                isHasSame = true;
            }
        }
        return isHasSame;
    }
}
